package com.cloudptt.wp.ui.address.workspace;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.func.crsc.CrscListener;
import com.cloudptt.api.product.func.crsc.FuncNumOb;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.CrscOperator;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.UiDlg;
import com.cloudptt.wp.ui.message.SessionFuncActivity;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.UserInfo;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.Vector;

public class WorkspaceFragment extends Fragment implements AdapterView.OnItemClickListener, IFuncDlgClick, CrscListener,AdapterView.OnItemLongClickListener, DialogInterface.OnClickListener {
	private Context ctx = null;
	private View mRootView = null;
	private ListView listView = null;
	private ListView loginFuncListView = null;
	private FuncAdapter mAdapter;
	private String bindUuid = null;
	private String queryUuid = null;
	//	private String bindFuncNum = null;
	private int selectedPos = 0;

	private List<FuncNumOb> funcNumObList = new Vector<>();
	private LoginFuncObAdapter funcObAdapter = null;
	private CrscOperator op = null;
	public WorkspaceFragment() {
	}
	public WorkspaceFragment(Context ctx)
	{
		this.ctx = ctx;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if(mRootView != null){
			return mRootView;
		}
		mRootView = inflater.inflate(R.layout.page_func, container, false);
		listView = (ListView) mRootView.findViewById(R.id.funcListView);
		listView.setOnItemClickListener(this);
		mAdapter = new FuncAdapter(ctx);
		listView.setAdapter(mAdapter);

		loginFuncListView = (ListView) mRootView.findViewById(R.id.loginFuncListView);
		loginFuncListView.setOnItemClickListener(this);
		loginFuncListView.setOnItemLongClickListener(this);
		return mRootView;
	}

	@Override
	public void onResume() {
		super.onResume();
		if(ctx != null) {
			SysApplication app = ((SysApplication) ctx.getApplicationContext());
			Product product = app.getProduct();
			if (product != null) {
				product.setCrSCListener(this);
				bindUuid = product.getFuncUuid();
				funcNumObList = product.getFuncNumObList();
				Log.debug(this.getClass(), "onResume funcNumObList = " + funcNumObList);
				updateFuncObList();

				op = (CrscOperator) product.getOperator(ProductConst.Func_Crsc);
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Log.debug(this.getClass(),"onItemClick position = " + position);
		if(R.id.funcItemLy == view.getId())
		{
			doFuncItemClick(position);
		}
		else if(R.id.funcNumLy == view.getId())
		{
			Log.debug(this.getClass(),"onItemClick position = " + position);
			selectedPos = position;
			funcObAdapter.setSelectedPos(selectedPos);
			updateFuncObList();
		}
	}

	private void doFuncItemClick(int position)
	{
		String title = "";
		Log.debug(this.getClass(),"onItemClick position = " + position);
		switch (position) {
			case 0:
				title = getString(R.string.func_login);
				UiDlg.showFuncDialog(ctx,position,title,this);
				break;
			case 1:
				title = getString(R.string.func_query);
				UiDlg.showFuncDialog(ctx,position,title,this);
				break;
			case 2:
				title = getString(R.string.func_addressing);
				UiDlg.showFuncDialog3(ctx,position,title,this);
				break;
			case 3:
				title = getString(R.string.func_local);
				UiDlg.showFuncDialog3(ctx,position,title,this);
				break;
			case 4:
				if(funcNumObList.size() <= 0)
				{
					CommDlg.showToast(ctx,R.string.func_func_num_check);
					return;
				}
				else {
					Intent intent = new Intent();
					intent.setClass(ctx, SessionFuncActivity.class);
					String[] funcNumArr = toFuncObNumArr();
					Log.debug(this.getClass(),"onCreate funcNumArr =  "+ funcNumArr);
					intent.putExtra(SessionFuncActivity.KEY, funcNumArr);
					startActivity(intent);
				}
				break;
			case 5:
				title = getString(R.string.func_compulsory);
				UiDlg.showFuncDialog2(ctx,position,title,this);
				break;
			case 6:
				title = getString(R.string.func_query_self);
				op.subcribeFuncSelf();
				break;
			default:
				break;
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		selectedPos = position;
		String item1 = ctx.getString(R.string.func_logout);
		String[] list = new String[]{item1};
		UiDlg.showListDialog(ctx, list, this);
		return false;
	}
	@Override
	public void onClick(DialogInterface dialog, int index) {
		if(index == 0)
		{
			if(op != null) {
				if(selectedPos > funcNumObList.size())
				{
					selectedPos = 0;
				}
				if(0 < funcNumObList.size()) {
					FuncNumOb ob = funcNumObList.get(selectedPos);
					if (ob != null) {
						op.sendFuncLogx(false, bindUuid, ob.getFuncNum(), false, "");
					}
				}
			}
		}
	}

	@Override
	public void onClickOk(int type,String val1,String val2) {
		Log.debug(this.getClass(),"onClickOk type = " + type + " val1 = " + val1 + " val2 = " + val2);
		if(val1 == null
				|| val1.equals(""))
		{
			return;
		}
		if(op != null)
		{
			switch (type) {
				case 0:
					if(isExist(val1))
					{
						String welcomeMessage = ctx.getString(R.string.func_num_exist);
						CommDlg.show(ctx, welcomeMessage, Toast.LENGTH_LONG);
					}
					else
					{
						this.bindUuid = UUID.randomUUID().toString();
						String bindFuncNum =  AddrInfo.toUrlFromNum(val1);
						op.sendFuncLogx(true, bindUuid,bindFuncNum,false,"");
					}
					break;
				case 1:
					queryUuid = UUID.randomUUID().toString();
					String queryFuncNum = AddrInfo.toUrlFromNum(val1);
					op.subcribeFunc(queryUuid, queryFuncNum);
					break;
				case 2:
					if(selectedPos > funcNumObList.size())
					{
						selectedPos = 0;
					}
					if(0 < funcNumObList.size()) {
						FuncNumOb ob = funcNumObList.get(selectedPos);
						if (ob != null) {
							if(val2 != null
									&& val2.equals("VIDEO")) {
								callFuncNum(val1, ob.getFuncNum(),true);
							}
							else
							{
								callFuncNum(val1, ob.getFuncNum(),false);
							}
						}
					}
					else
					{
						String welcomeMessage = ctx.getString(R.string.func_num_null);
						CommDlg.show(ctx, welcomeMessage, Toast.LENGTH_LONG);
					}
					break;
				case 3:
					if(selectedPos > funcNumObList.size())
					{
						selectedPos = 0;
					}
					Log.debug(this.getClass(),"onClickOk funcNumObList.size() = " + funcNumObList.size());
					if(0 < funcNumObList.size()) {
						FuncNumOb ob = funcNumObList.get(selectedPos);
						Log.debug(this.getClass(),"onClickOk ob = " + ob + " selectedPos = " + selectedPos );
						if (ob != null) {
							if(val2 != null
								&& val2.equals("VIDEO")) {
								callFuncNum(val1, ob.getFuncNum(), true);
							}
							else
							{
								callFuncNum(val1, ob.getFuncNum(), false);
							}
						}
					}
					else
					{
						String welcomeMessage = ctx.getString(R.string.func_num_null);
						CommDlg.show(ctx, welcomeMessage, Toast.LENGTH_LONG);
					}
//					callFuncNum(val1,"");
					break;
				case 5:
					if(val2 == null
							|| val2.equals(""))
					{
						return;
					}
//					if(isExist(val1))
//					{
//						String welcomeMessage = ctx.getString(R.string.func_num_exist_force);
//						CommDlg.show(ctx, welcomeMessage, Toast.LENGTH_LONG);
//					}
//					else
					{
						String uuid = UUID.randomUUID().toString();
						String funcNum = AddrInfo.toUrlFromNum(val1);
						String initiateId = AddrInfo.toUrlFromNum(val2);
						op.sendFuncLogx(false, uuid, funcNum, true, initiateId);
					}
					break;
				default:
					break;
			}
		}
	}

	public void callFuncNum(String toFuncNum,String selfFuncNum,boolean hasVideo)
	{
		Log.debug(this.getClass(),"callFuncNum toFuncNum = " + toFuncNum + " selfFuncNum = " + selfFuncNum + " hasVideo = " + hasVideo);
		SysApplication app = ((SysApplication) ctx.getApplicationContext());
		Product product = app.getProduct();
		String name = toFuncNum;
		boolean isEmergency = false;
		if(toFuncNum.equals("299"))
		{
			isEmergency = true;
		}
//		String num = AddrInfo.toUrlFromNum(toFuncNum);
		UserInfo userInfo = new UserInfo(AddrInfo.UserType_User,name,toFuncNum);
		product.getPCallEventAdapter().makePrivateCall(userInfo, CallAttr.CallType_Private,hasVideo,isEmergency,selfFuncNum);
	}
	@Override
	public void onInitLogxResult(String uuid,List<FuncNumOb> funcNumList)
	{
		Log.debug(this.getClass(),"onInitLogxResult uuid = " + uuid + " bindUuid = " + bindUuid + " funcNumList = " + funcNumList);
		if(bindUuid != null
				&& bindUuid.equals(uuid))
		{
			if(funcNumList.size() == 1)
			{
				FuncNumOb ob = funcNumList.get(0);
				Log.debug(this.getClass(),"onInitLogxResult ob = " + ob);
				if(ob.isActive()) {
					SysApplication app = ((SysApplication) ctx.getApplicationContext());
					Product product = app.getProduct();
//					product.setFunNumForReportData(ob.getFuncNumDesc());

					String welcomeMessage = getString(R.string.func_bind_suc, ob.getFuncNumDesc());
					CommDlg.show(ctx, welcomeMessage, Toast.LENGTH_LONG);
				}
				else
				{
					String welcomeMessage = getString(R.string.func_unbind_suc, ob.getFuncNumDesc());
					CommDlg.show(ctx, welcomeMessage, Toast.LENGTH_LONG);
				}
				updateFuncObList(ob);
				this.selectedPos = 0;
			}
		}
		else
		{
			if(funcNumList != null
				&& funcNumList.size() > 0)
			{
				StringBuffer strBuf = new StringBuffer();
				for(Iterator<FuncNumOb> itor = funcNumList.iterator();itor.hasNext();)
				{
					FuncNumOb ob = itor.next();
					Log.debug(this.getClass(),"onInitLogxResult no uuid ob = " + ob);
					strBuf.append(ob.getFuncNumDesc()).append(" ");
					updateFuncObList(ob);
				}
//				String welcomeMessage = getString(R.string.func_unbind_udm,strBuf);
				CommDlg.show(ctx, strBuf, Toast.LENGTH_LONG);
			}
			Log.debug(this.getClass(),"onInitLogxResult end funcNumObList = " + funcNumObList);
		}
		updateFuncObList();
	}
	@Override
	public void onQueryResult(List<FuncNumOb> userList)
	{
		if(userList == null
				|| userList.size() <= 0)
		{
			String result = getString(R.string.func_query_failed);
			CommDlg.show(ctx, result, Toast.LENGTH_LONG);
			return;
		}
		StringBuffer buffer = new StringBuffer();
		for (Iterator<FuncNumOb> itor = userList.iterator();itor.hasNext();)
		{
			FuncNumOb ob = itor.next();
			Log.debug(this.getClass(),"onQueryResult ob = " + ob);
			buffer.append(ob.getUserDesc()).append("\r\n");
		}
		Log.debug(this.getClass(),"onQueryResult buffer = " + buffer);
		CommDlg.show(ctx, buffer.toString(), Toast.LENGTH_LONG);
		return;
	}
	@Override
	public void onCompulsoryResult(String num,String user)
	{
		num = AddrInfo.toNumFromSipUrl(num);
		user = AddrInfo.toNumFromSipUrl(user);
		String resultStr = getString(R.string.func_compulsory_result, num,user);
		Log.debug(this.getClass(),"onCompulsoryResult resultStr = " + resultStr);
		CommDlg.show(ctx, resultStr, Toast.LENGTH_LONG);

		SysApplication app = ((SysApplication) ctx.getApplicationContext());
		Product product = app.getProduct();
		if (product != null) {
			product.setCrSCListener(this);
			bindUuid = product.getFuncUuid();
			funcNumObList = product.getFuncNumObList();
			Log.debug(this.getClass(), "onCompulsoryResult end funcNumObList = " + funcNumObList);
			updateFuncObList();
		}
//		CommDlg.showWarrningDlg(ctx,resultStr,null);
	}

	@Override
	public void onFuncPublishRsp(int code, String errStr) {
		Log.debug(this.getClass(),"onFuncPublishRsp code = " + code + " errStr = " + errStr);
		CommDlg.show(ctx, errStr, Toast.LENGTH_LONG);
	}

	private void updateFuncObList(FuncNumOb newOb)
	{
		Log.debug(this.getClass(),"updateFuncObList newOb = " + newOb + " funcNumObList = " + funcNumObList);
		if (newOb != null)
		{
			if(newOb.isActive())
			{
				if(!isExist(newOb.getFuncNum())) {
					funcNumObList.add(newOb);
				}
			}
			else
			{
				for(Iterator<FuncNumOb> itor = funcNumObList.iterator();itor.hasNext();)
				{
					if(itor != null) {
						FuncNumOb oldOb = itor.next();
						Log.debug(this.getClass(), "updateFuncObList newOb = " + oldOb);
						if (oldOb != null
								&& oldOb.isSameOne(newOb)) {
							itor.remove();
						}
					}
				}
			}
		}
		Log.debug(this.getClass(),"updateFuncObList end funcNumObList = " + funcNumObList);
	}
	private void updateFuncObList()
	{
		Log.debug(this.getClass(),"updateFuncObListView end funcNumObList = " + funcNumObList);
		if(funcObAdapter != null)
		{
			funcObAdapter.setFuncNumObList(funcNumObList);
			funcObAdapter.notifyDataSetChanged();
		}
		else
		{
			funcObAdapter = new LoginFuncObAdapter(ctx, funcNumObList);
			funcObAdapter.setSelectedPos(selectedPos);
			loginFuncListView.setAdapter(funcObAdapter);
		}
	}

	private String[] toFuncObNumArr()
	{
		String[] arr = new String[funcNumObList.size()];
		int index = 0;
		for(Iterator<FuncNumOb> itor = funcNumObList.iterator();itor.hasNext();)
		{
			FuncNumOb ob = itor.next();
			arr[index] = ob.getFuncNumDesc();
			index ++;
		}
		return arr;
	}
	private boolean isExist(String num)
	{
		for(Iterator<FuncNumOb> itor = funcNumObList.iterator();itor.hasNext();)
		{
			FuncNumOb ob = itor.next();
			Log.debug(this.getClass(),"isExist num = " + num + " ob = " + ob);
			if(ob.isSameOne(num))
			{
				return true;
			}
		}
		return false;
	}
}
